import { DataTypes, Model } from 'sequelize';
import sequelize from '../db';

/**
 * 租户权限关联模型
 */
class TenantPermission extends Model {
  public id!: string;
  public tenantId!: string;
  public permissionId!: string;
  public source!: 'plan' | 'extra'; // 权限来源
  public grantedBy?: string; // 授权人
  public grantedAt?: Date; // 授权时间
  public expiresAt?: Date; // 过期时间
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  /**
   * 是否已过期
   */
  isExpired(): boolean {
    if (!this.expiresAt) return false;
    return new Date() > this.expiresAt;
  }

  /**
   * 是否来自套餐
   */
  isFromPlan(): boolean {
    return this.source === 'plan';
  }

  /**
   * 是否为额外授予
   */
  isExtra(): boolean {
    return this.source === 'extra';
  }
}

TenantPermission.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'tenant_id',
    },
    permissionId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'permission_id',
    },
    source: {
      type: DataTypes.ENUM('plan', 'extra'),
      allowNull: false,
      defaultValue: 'plan',
    },
    grantedBy: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'granted_by',
    },
    grantedAt: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'granted_at',
    },
    expiresAt: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'expires_at',
    },
  },
  {
    sequelize,
    tableName: 'tenant_permissions',
    underscored: true,
    timestamps: true,
  },
);

export default TenantPermission;

